<?php
/**
 * Created by PhpStorm.
 * User: 87976
 * Date: 2018/1/29
 * Time: 14:00
 */

namespace App\Services\Album;


use App\Abstracts\TemplateAbstract;
use App\Repositories\Album\AlbumGoodsCategoryRepository;
use App\Repositories\Goods\GoodsWidRepository;
use App\Services\Goods\GoodsService;
use Symfony\Component\Translation\Exception\NotFoundResourceException;

/**
 * Class AlbumGoodsCategoryService
 * @package App\Services\Album
 */
class AlbumGoodsCategoryService extends TemplateAbstract
{

    /**
     * @var AlbumGoodsCategoryRepository
     */
    protected $albumGoodsCategoryRepository;

    /**
     * @var GoodsService
     */
    protected $goodsService;

    protected $goodsWidRepository;


    public function __construct(AlbumGoodsCategoryRepository $albumGoodsCategoryRepository, GoodsService $goodsService, GoodsWidRepository $goodsWidRepository)
    {
        $this->albumGoodsCategoryRepository = $albumGoodsCategoryRepository;

        $this->goodsService = $goodsService;

        $this->goodsWidRepository = $goodsWidRepository;
    }

    /**
     * @author Jerry
     * @param array $data
     * @return array|mixed
     */
    public function handle(array $data)
    {
        $albumCategory = $this->albumGoodsCategoryRepository->findGoodsCategoryByAlbumId($data['id']);
        
        if (empty($albumCategory)) {
            throw new NotFoundResourceException('分类数据为空!');
        }

        $goods = $this->getCategoryGoodsCacheByCategoryId($albumCategory['category_id'], $albumCategory['goods_where']);

        $goods = $this->goodsService->formatGoodsTransformList($goods);

        $data['goods_data'] = $goods;

        unset($data['album_id']);

        return $data;
    }

    protected function getCategoryGoodsCacheByCategoryId(int $categoryId, int $goodsWhere, int $isHidePromote = 0)
    {
        $wid = 8;

        $ids = $this->albumGoodsCategoryRepository->findCategoryGoodsCacheByCategoryId($categoryId, $goodsWhere, $wid, $isHidePromote);

        if (empty($ids)) {
            return [];
        }

        $data = [];

        foreach ($ids as $id) {
            $goods = $this->getGoodsInfoByGoodsId($id);

            if (empty($goods)) {
                continue;
            }

            $data[] = (array) $goods;
        }

        return $data;
    }

    protected function getGoodsInfoByGoodsId($goodsId, $wid = 8)
    {
        return $this->goodsWidRepository->findGoodsWidInfoByGoodsId($goodsId, $wid);
    }

}